import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import sun.net.www.http.HttpClient;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * User: yuanjianpeng
 * Date: 2018/10/17
 * Project: httpclient
 * Version: 1.0
 * Description:
 */
public class ConnetPoolTest {

    public static void main(String[] args) {

        PoolingHttpClientConnectionManager conMgr = new PoolingHttpClientConnectionManager(); //HttpClientConnectionManager的子类，可以使用HttpsRegisTryBuilder引入证书等注册事件
        conMgr.setMaxTotal(4); //最大线程数
        conMgr.setDefaultMaxPerRoute(3); //默认连接数

        final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(conMgr).build();

        final HttpGet httpGet = new HttpGet("http://127.0.0.1:6066");

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(500).
                setConnectTimeout(3000).build();

        httpGet.setConfig(requestConfig);

        ExecutorService executorService = Executors.newFixedThreadPool(6);

        for(int i=0;i<6;i++){
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        CloseableHttpResponse response = httpClient.execute(httpGet);
                    } catch (SocketTimeoutException e) {
                        e.printStackTrace();
                    }catch (ConnectionPoolTimeoutException e) {
                        e.printStackTrace();
                    }catch (ConnectException e) {
                        e.printStackTrace();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
